package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.assertj.core.util.Lists;
import org.assertj.core.util.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 用户添加
     * @param userDto
     * @return
     */
    @Override
    @Transactional
    public UserVo addUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(user.getEmail());
        user.setNickName(user.getRealName());
        user.setDataState(SuperConstant.DATA_STATE_0);
        //todo 需要设置默认，并要加密
        String password = "itcast";
        user.setPassword(password);
        userMapper.insert(user);
        if (user.getId() == null) {
            throw new RuntimeException("User ID not generated after insert");
        }
        //保存用户角色中间表
        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        userRoleMapper.batchInsert(userRoles);
        return BeanUtil.toBean(user, UserVo.class);
    }

    /**
     * 修改用户
     * @param userDto
     */
    @Override
    @Transactional
    public void updateUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(userDto.getEmail());
        userMapper.update(user);

        //删除旧的角色关联
        userRoleMapper.deleteUserRoleByUserId(user.getId());

        //重新保存角色中间表
        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        userRoleMapper.batchInsert(userRoles);
    }

    /**
     * 启用或禁用用户
     * @param id
     * @param status
     */
    @Override
    public void isEnable(Long id, String status) {
        User user = userMapper.selectByid(id);
        user.setDataState(status);
        userMapper.updateByStatus(user);
    }

    /**
     * 用户列表
     * @param userDto
     * @return
     */
    @Override
    public List<UserVo> list(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        return userMapper.selectList(user);
    }

    /**
     * 用户分页
     * @param userDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<UserVo> findUserPage(UserDto userDto, int pageNum, int pageSize) {
        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())) {
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }
        //构建分页对象
        PageHelper.startPage(pageNum, pageSize);
        Page<List<User>> page = userMapper.selectPage(userDto);
        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);
        if (!EmptyUtil.isNullOrEmpty(pageResponse.getRecords())) {
            List<Long> userIds = pageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            //查询对应角色
            List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(userIds);
            //装配数据
            pageResponse.getRecords().forEach(n -> {
                //装配角色
                Set<String> roleVoIds = Sets.newHashSet();
                Set<String> roleVoLabels = Sets.newHashSet();
                roleVoList.forEach(r -> {
                    if (String.valueOf(n.getId()).equals(r.getUserId())) {
                        roleVoIds.add(String.valueOf(r.getId()));
                        roleVoLabels.add(r.getRoleName());
                    }
                });
                n.setRoleLabels(roleVoLabels);
                n.setRoleVoIds(roleVoIds);
            });
        }
        return pageResponse;
    }

    /**
     * 删除用户
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        //删除用户于角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        userMapper.deleteById(userId);
    }

    /**
     * 重置密码
     * @param userId
     */
    @Override
    public void resetPasswords(Long userId) {
        userMapper.updatePassword(userId);
    }
}
























